/**
 * Created by cchen on 2015/5/15.
 */
var async = require('async');
var Community = mongoose.model('community');
var mysql = require('../../common/utils/mysqlUtil')
var communityService = require('../communityService');


exports.addRewardRule = function (rule, callback) {
    rule.create_time = new Date().getTime();
    rule.update_time = new Date().getTime();
    exports.mysqlInsert("voucher_reward_rule", rule, function (err, result) {
        callback(err, result)
    })

}

exports.updateRewardRule = function (rule, callback) {
    rule.update_time = new Date().getTime();
    rule.id = rule._id;
    delete rule._id;
    delete rule.voucher_name;
    delete rule.type;
    console.log(rule);
    exports.mysqlUpdate("voucher_reward_rule", rule, function (err, result) {
        callback(err, result)
    })
}

exports.deleteRewardRule = function (rule, callback) {
    console.log(rule)
    rule.id = rule.objId;
    exports.mysqlDelete("voucher_reward_rule", rule, function (err, result) {
        callback(err, result)
    })

}

exports.getRewardRuleList = function (filter, callback) {
    var filterStr = ''
    if (filter.filter !== "all") {
        filterStr = " && v.community_name like '%" + filter.filter + "%'"
    }
    exports.mysqlSelect("t.type,v.id as objId ,v.community_id, from_unixtime(v.from_time/1000, '%Y-%m-%d') as from_time, from_unixtime(v.to_time/1000, '%Y-%m-%d') as to_time, v.reward_expiredate_length, v.voucher_type_id, t.voucher_name, v.reward_source, v.community_name",
        "voucher_reward_rule as v,voucher_type as t ",
        "t.id=v.voucher_type_id " + filterStr,
        null,
        function (err, result) {
            callback(err, result)
        });
}


exports.getCommunity = function (communityId, callback) {
    Community.findById(communityId + "", callback);
    //communitService.getCommunityListByFilter({_id:communityId+""},callback);
}

exports.getVoucherTypeList = function (callback) {
    exports.mysqlSelect(null, "voucher_type", null, null, function (err, result) {
        callback(err, result);
    })

}


exports.mysqlSelect = function (feilds, tables, where, sort, callback) {
    var selectStr = "select " + (feilds ? feilds : "*") + " from " + tables + "" + (where ? " where " + where : "") + (sort ? " " + sort : "");
    console.log(selectStr)
    mysql.query(selectStr, function (err, result) {
        callback(err, result);
    });
}

exports.mysqlInsert = function (table, obj, callback) {
    mysql.query("insert into " + table + " set?", obj, callback);
}

exports.mysqlUpdate = function (table, obj, callback) {
    mysql.query("update " + table + " set ? where id=" + obj.id, obj, callback);
}

exports.mysqlDelete = function (table, obj, callback) {
    console.log(table)
    console.log(obj)
    mysql.query("delete from " + table + " where id=" + obj.id, obj, callback);
}
